﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};

Axis.Admin.ListNews = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        thisObj.EventClick();
        $("button").button();
        var cmaskdate = new CMaskDate({
            dateTimePicker: true

        });
        cmaskdate.Init($("#txtEndDate,#txtStartDate"));
        thisObj.DropdownChecklist.Init();
    },
    DropdownChecklist: {
        Instance: null,
        Init: function () {
            $("#FormEdit,#FormFilter").show();
            var thisObj = this;
            thisObj.Instance = new CDropDownCheckList({ width: 200, maxDropHeight: 110, firstItemChecksAll: true });
            thisObj.Instance.Init("#FormEdit select[multiple]");
            thisObj.Instance.Init("#FormFilter select[multiple]");
            $("#FormEdit,#FormFilter").hide();
        },
        Clear: function () {
            var thisObj = this;
            $("#FormEdit select[multiple]").find("option").removeAttr("selected");
            thisObj.Refresh();
        },
        Refresh: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                thisObj.Instance.Refresh();
            }
        }
    },
    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        Init: function () {
            var thisObj = this;
            var options = {
                url: 'Service/StaticGrid.ashx?Action=GET',
                datatype: "json",
                colNames: [
                    'ID', 'Mã', 'Tên','CategoryID','Content', 'Action'
                ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 50, frozen: true, hidden: true, hidedlg: true },
                    { name: 'Code', index: 'Code', width: 200, hidden: true, frozen: true, hidedlg: true },
                    { name: 'Title', index: 'Title', width: 550, frozen: true },
                    { name: 'CategoryID', index: 'CategoryID', width: 100, hidden: true, hidedlg: true },
                    { name: 'Content', index: 'Content', width: 150, hidden: true },
                    { name: 'Action', index: 'Action', width: 55, align: 'center' }
                ],

                gridComplete: function () {

                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {

                },
                onSelectRow: function (rowid, status, e) {

                },
                ondblClickRow: function (rowid, iRow, iCol, e) {

                },
                afterInsertRow: function (rowid, aData, addData) {

                    var action = $.string.Format("<img class='imgAction' src='../../Images/16x16/edit.png' onclick=\"ShowEdit('{0}')\"/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'Action', action);
                    var iconStatus = 's_enable.png';
                    if (aData.Status == '-1')
                        iconStatus = 's_delete.png';
                    if (aData.Status == '1')
                        iconStatus = 's_visible.png';
                    var StatusString = $.string.Format("<img class='imgAction' src='../../Images/16x16/{0}' onclick=\"ActionStatus('{1}',{2})\"/>", iconStatus, rowid, aData.Status);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'StatusString', StatusString);


                },
                multiselect: false,
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                //forceFit: true,
                shrinkToFit: false,
                rowNum: 20,
                pager: thisObj.PagesID
            };
            thisObj.GridObj = new CGrid(options);
            thisObj.GridObj.Init(thisObj.ID);
            thisObj.GridObj.NavGrid();
            thisObj.GridObj.FrozenColumns();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.GridObj)
                thisObj.GridObj.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.GridObj) {
                return thisObj.GridObj.SelectRow();
            }
            return null;
        },
        SetNewUrl: function (url) {
            var thisObj = this;
            thisObj.GridObj.setGridParam({ url: url });
            thisObj.Reload();

        },
        GetRowData: function (id) {
            var thisObj = this;
            return $(thisObj.ID).jqGrid('getRowData', id);
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var wDialog = $(window).width() / 2 + 100;
            var hDialog = $(window).height() *3/4-80;
            var thisObj = this;
            thisObj.ClearForm();
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Sửa bài viết",
                    width: wDialog,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {
                        if (CKEDITOR.instances["txtFullContent"]) {
                        }
                        else {
                            var config = {
                                width: wDialog-10,
                                height: hDialog,
                                toolbar: 'MyToolbar',
                                filebrowserBrowseUrl: '/ckfinder/ckfinder.html',
                                filebrowserImageBrowseUrl: '/ckfinder/ckfinder.html?type=Images',
                                filebrowserFlashBrowseUrl: '/ckfinder/ckfinder.html?type=Flash',
                                filebrowserUploadUrl: '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Files',
                                filebrowserImageUploadUrl: '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Images',
                                filebrowserFlashUploadUrl: '/ckfinder/core/connector/aspx/connector.aspx?command=QuickUpload&type=Flash'
                            };
                            CKEDITOR.replace("txtFullContent", config);
                        }
                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm bài viêt");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    $(thisObj.ID).find("#txtLoginName").focus();
                    buttonText = "Thêm";
                    $("#txtStatus").attr('checked', 'checked');
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Sửa: " + opts.Title);
                    $.each(opts, function (key, value) {
                        switch (key) {
                            case 'Content':
                                if (CKEDITOR && CKEDITOR.instances["txtFullContent"])
                                    CKEDITOR.instances["txtFullContent"].setData(value);
                                break;
                            default:
                                $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                        }

                    });

                    buttonText = "Hiệu chỉnh";
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.ListNews.Update(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Đóng",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        LoadNews: function (opt) {

        },
        ClearForm: function () {
            $("#FormEdit").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option[Default-Value='1']").attr("value");
                    $this.val(value);
                }

            });
            $("#FormEdit").find("[data-role='INSERT']").hide();
            if (CKEDITOR && CKEDITOR.instances["txtIntro"])
                CKEDITOR.instances["txtIntro"].setData('');
            if (CKEDITOR && CKEDITOR.instances["txtFullContent"])
                CKEDITOR.instances["txtFullContent"].setData('');

            Axis.Admin.ListNews.DropdownChecklist.Clear();
        }
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        $("#FormEdit").find("[data-field]").each(function () {
            var $this = $(this);
            if ($this.attr("data-field")) {
                var key = $this.attr("data-field");
                var value = $this.val();
                data[key] = value;
            }
        });
        if (CKEDITOR && CKEDITOR.instances["txtFullContent"])
            data.Content = CKEDITOR.instances["txtFullContent"].getData();
        data.Action = type;
        if (typeof USER_ID != "undefined") {
            data.UserID = USER_ID;
            data.SecrectToken = SECRECT_TOKEN;
        }
        $.Ajax({
            url: 'Service/StaticAction.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        thisObj.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    Filter: function (type, opts) {
        var thisObj = this;
        var data = {};
        $("#FormFilter").find("[data-field]").each(function () {
            var $this = $(this);
            if ($this.attr("data-field")) {
                var key = $this.attr("data-field");
                var value = $this.val();
                if ($this.attr('type') == 'checkbox') {
                    if ($this.is(':checked'))
                        value = 1;
                }

                if ($this.attr("role") == "datepicker") {
                    value = $.CFormat.FormatDate(value, "yyyy/MM/dd HH:mm", "vi-VN", "en-US");
                }
                if (key == "Tags") {
                    if (value && $.isArray(value)) {
                        value = value.join(",");
                    }
                }
                data[key] = value;
            }
        });
        var url = 'Service/GetNewsList.ashx?Action=GET&Context=Backend';
        for (var key in data) {
            var attrName = key;
            var attrValue = data[key];
            if (attrValue == null)
                attrValue = "";
            url += $.string.Format("&{0}={1}", attrName, attrValue);
        }
        thisObj.Grid.SetNewUrl(url);

    },
    DialogFilter: {
        ID: "#FormFilter",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Tìm bài viết",
                    width: 300,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {
                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "Tìm";

            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.ListNews.Filter(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Đóng",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },

        ClearForm: function () {
            $("#FormFilter").find("[data-field]").each(function () {
                var $this = $(this);
                $this.val("");
                if ($this.is("select")) {
                    var value = $this.find("option[Default-Value='1']").attr("value");
                    $this.val(value);
                }

            });
            $("#FormFilter").find("[data-role='INSERT']").hide();

            Axis.Admin.ListNews.DropdownChecklist.Clear();
        }
    },
    EventClick: function () {
        var thisObj = this;
        $("#btnSelectImg").click(function () {
            var finder = new CKFinder();
            finder.resourceType = 'Images';
            finder.startupPath = "Images:/News/";
            finder.selectActionFunction = function (fileUrl) {
                $('#txtImage').val(fileUrl);
            };
            finder.popup();
        });
        $("#btnSelectThumbnail").click(function () {
            var finder = new CKFinder();
            finder.resourceType = 'Images';
            finder.startupPath = "Images:/News/";
            finder.selectActionFunction = function (fileUrl) {
                $('#btnSelectThumbnail').val(fileUrl);
            };
            finder.popup();
        });

        $("#imgUserAdd").click(function () {
            thisObj.DialogEdit.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else alert("Please Select Row");
        });
        $("#imgUserDel").click(function () {
            thisObj.DeleteNews();

        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();
        });

    },
    DeleteNews: function (id) {
        var thisObj = this;
        var rowData = thisObj.Grid.SelectRow();
        if (typeof id != 'undefined') {
            rowData = thisObj.Grid.GetRowData(id);
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa bài viết",
                    Content: $.string.Format("Bạn có chắc muốn xóa bài viết: [{0}].", rowData.Title),
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa bài viết",
                    Content: "Vui lòng chọn bài viết cần xóa.",
                });
            }
        }
        else {
            $.CAlert.Confirm({
                Title: "Xóa bài viết",
                Content: $.string.Format("Bạn có chắc muốn xóa bài viết đã chọn", ''),
            }, function (isOK) {
                if (isOK) {
                    rowData.IDs = $(thisObj.Grid.ID).jqGrid('getGridParam', 'selarrrow').toString();
                    thisObj.Update("DELETEMULTI", rowData);
                }
            });

        }
    }
};
$(function () {
    Axis.Admin.ListNews.Init();
});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.ListNews;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}
function DeleteNews(rowID) {
    Axis.Admin.ListNews.DeleteNews(rowID);
}
function FormatGridDescription(cellvalue, options, rowObject) {
    if (cellvalue.indexOf("project_desc_panel") == -1) {
        return '<div class="project_desc_panel">' + cellvalue + '</div>';
    }
    else
        return cellvalue;

}
function ActionStatus(rowID, Status) {
    var thisObj = Axis.Admin.ListNews;
    var newStatus = "Active";
    var action = "DEACTIVE";
    Status = parseInt(Status);
    if (Status == 1) {
        newStatus = "DeActive";
        action = "ACTIVE";
    }
    if (Status == -1)
        return;
    var rowData = { ID: rowID };
    if (rowData && rowData.ID) {
        $.CAlert.Confirm({
            Title: "Cập nhật trang thái thái viết bài viết",
            Content: $.string.Format("Bạn có chắc muốn thay đôi trạng thái bài viết", newStatus),
        }, function (isOK) {
            if (isOK)
                thisObj.Update(action, rowData);
        });
    }
    else {
        $.CAlert.Alert({
            Title: "Xóa bài viết",
            Content: "Vui lòng chọn bài viết cần xóa.",
        });
    }


}